package com.quanyan.place.service;

import com.quanyan.common.constants.CacheConstants;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbAdminUserExample;
import com.quanyan.place.mapper.TbAdminUserMapper;

import com.quanyan.redisCluster.utils.RedisKey;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Hugo.Wwg
 * @Since 2016-04-18 公用查询cache
 */
@Service
public class CacheService {

    @Autowired
    private PlaceRedisTemplate placeRedisCache;

    @Autowired
    private TbAdminUserMapper adminUserMapper;

    public TbAdminUser getAdminUser(Integer adminUserId) {
        Object obj = placeRedisCache.get(CacheConstants.PLACE_COMMON_DATA + adminUserId.toString());
        TbAdminUser tbAdminUser = null;
        if (obj != null) {
            return (TbAdminUser) obj;
        }

        TbAdminUserExample example = new TbAdminUserExample();
        example.createCriteria().andIdEqualTo(adminUserId);
        List<TbAdminUser> adminUserList = adminUserMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(adminUserList)) {
            tbAdminUser = adminUserList.get(0);
            placeRedisCache.set(CacheConstants.PLACE_COMMON_DATA + tbAdminUser.getId().toString(),tbAdminUser);
            return tbAdminUser;
        }

        return tbAdminUser;
    }

    // 获取当前版本
    public long getCurrentNumber(String biz, String key) {
        return placeRedisCache.incrBy(biz + "_" + key, 0);
    }

    // 获取流水号 + 1
    public long getRunningNumber(String biz, String key) {
        return placeRedisCache.incr(biz + "_" + key);
    }

    // 重置流水号
    public void resetRunningNumber(String biz, String key) {
        RedisKey rKey = new RedisKey("", (biz + "_" + key));
        placeRedisCache.delteKey(rKey);
        return;
    }
}
